﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml.Linq;


public static class EnumHelper
{
    public static Enum GetEnum(this object value, Type enumType)
    {
        if (!enumType.IsNullOrEmpty() && enumType.IsEnum && Enum.TryParse(enumType, value.ToString(), out var result))
        {
            return (Enum)result;
        }
        return null;
    }
    public static string GetEnumDescription(this object value,Type enumType)
    {
        var result = GetEnum(value, enumType);
        return result==null?value.ToString(): result.GetEnumDescription();
    }
    public static CategoryAttribute GetEnumCategoryAttribute(this Enum value)
    {
        string name = value.ToString();
        var field = value.GetType().GetField(name);
        var attribute = (CategoryAttribute)Attribute.GetCustomAttribute(
        field,typeof(CategoryAttribute));
        return attribute;
    }
    public static DescriptionAttribute GetEnumDescriptionAttribute(this Enum value)
    {
        string name = value.ToString();
        var field = value.GetType().GetField(name);
        var attribute = (DescriptionAttribute)Attribute.GetCustomAttribute(
        field, typeof(DescriptionAttribute));
        return attribute;
    }
    public static string GetEnumDescription(this Enum value)
    {
        var attribute= value.GetEnumDescriptionAttribute();
        if (attribute == null)
            return value.ToString();
        return attribute.Description;
    }
    public static string GetEnumColor(this Enum value)
    {
        var attribute = value.GetEnumCategoryAttribute();
        if (attribute == null)
            return null;
        return attribute.Category;
    }
    public static List<T> GetEnumList<T>(this string value) where T : struct, Enum
    {
        if(string.IsNullOrEmpty(value))
            return new List<T> { default(T) };
        var array = value.Split(',');
        List<T> list = new List<T>();
        foreach (var item in array)
        {
            if(Enum.TryParse(item, out T enmuData))
            {
                list.Add(enmuData);
            }
        }
        return list;
    }
    public static string GetEnumListDescription<T>(this List<T> value) where T : struct, Enum
    {
        List<string> list = new List<string>();
        foreach (var item in value)
        {
            var str = item.GetEnumDescription();
            list.Add(str);
        }
        return string.Join(",", list);
    }
    public static string GetEnumListDescription<T>(this string value) where T : struct, Enum
    {
        var list = value.GetEnumList<T>();
        return list.GetEnumListDescription<T>();
    }
}